<template>
    <div class="modal-mask" v-show="props.modelValue" ref="customModalRef">
        <div class="modal-content">
            <div class="modal-header">
                <slot name="header">
                    <h2>默认的头部内容</h2>
                </slot>
                <button @click="closeModal" class="modal-close-btn">×</button>
            </div>
            <div class="modal-body">
                <slot></slot>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { createPopper } from "@popperjs/core";

const props = defineProps(["modelValue"]);
const emit = defineEmits(["update:modelValue"]);

const customModalRef = ref(null);
const popperInstance = ref(null);

// 在组件卸载时销毁 Popper 实例
onBeforeUnmount(() => {
    if (popperInstance.value) {
        popperInstance.value.destroy();
    }
});

const closeModal = () => {
    customModalRef.value.style.display = "none";
    emit('update:modelValue', false)
};

onMounted(() => {
    if (customModalRef.value) {
        // 使用 Popper.js 创建一个 Popper 实例
        popperInstance.value = createPopper(customModalRef.value, customModalRef.value, {
            placement: "bottom", // 指定模态框的位置
            strategy: 'absolute', // 定位策略
            modifiers: [
                {
                    name: "offset",
                    options: {
                        offset: [0, 0],
                    },
                }
            ],
        });
    }
});
</script>

<style scoped>
.modal-mask {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999;
}

.modal-content {
    background-color: white;
    width: 300px;
    border-radius: 5px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
    z-index: 1001;
}

.modal-header {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ccc;
    background: #10ac84;
    color: #fff;
}

.modal-header h2 {
    margin: 0;
}

.modal-close-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
    line-height: 1;
    color: #fff;
}

.modal-body {
    padding: 20px;
}
</style>
